﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace StartTool
{
    class Common
    {
        /// <summary>
		/// 执行cmd命令
		/// </summary>
		/// <param name="cmd"></param>
		public static void RunCmd(string cmd, string workPath = "")
        {
            cmd = cmd.Trim().TrimEnd('&') + "&exit";//说明：不管命令是否成功均执行exit命令，否则当调用ReadToEnd()方法时，会处于假死状态
            using (Process p = new Process())
            {
                p.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory() + workPath;// "C:\\Users\\fzr\\Desktop\\database"; //执行路径
                p.StartInfo.FileName = @"C:\Windows\System32\cmd.exe";
                p.StartInfo.UseShellExecute = false;        //是否使用操作系统shell启动
                p.StartInfo.RedirectStandardInput = true;   //接受来自调用程序的输入信息
                p.StartInfo.RedirectStandardOutput = true;  //由调用程序获取输出信息
                p.StartInfo.RedirectStandardError = true;   //重定向标准错误输出
                p.StartInfo.CreateNoWindow = true;          //不显示程序窗口
                p.Start();//启动程序

                //向cmd窗口写入命令
                p.StandardInput.WriteLine(cmd);
                p.StandardInput.AutoFlush = true;

                //获取cmd窗口的输出信息
                List<string> output = p.StandardOutput.ReadToEnd().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                CommonLog.LogWrite(string.Join("\n", output));
                List<string> outputErr = p.StandardError.ReadToEnd().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                CommonLog.LogWrite(string.Join("\n", outputErr));
                //output = p.StandardOutput;
                //outputErr = p.StandardError;
                p.WaitForExit();//等待程序执行完退出进程
                p.Close();
            }
        }
    }

    class Config
    {
        #region API函数声明

        [DllImport("kernel32")]//返回0表示失败，非0为成功
        private static extern long WritePrivateProfileString(string section, string key,
            string val, string filePath);

        [DllImport("kernel32")]//返回取得字符串缓冲区的长度
        private static extern long GetPrivateProfileString(string section, string key,
            string def, StringBuilder retVal, int size, string filePath);

        [DllImport("kernel32")]
        public static extern int GetPrivateProfileInt(string lpApplicationName, string lpKeyName, int nDefault, string lpFileName);


        #endregion

        #region 读Ini文件
        //Section参数、Key参数和IniFilePath不用再说，Value参数表明key的值，
        //而这里的NoText对应API函数的def参数，它的值由用户指定，是当在配置文件中没有找到具体的Value时，就用NoText的值来代替。
        //NoText 可以为null或""
        public static string ReadIniData(string Section, string Key, string NoText, string iniFilePath)
        {
            if (File.Exists(iniFilePath))
            {
                StringBuilder temp = new StringBuilder(1024);
                GetPrivateProfileString(Section, Key, NoText, temp, 1024, iniFilePath);
                return temp.ToString();
            }
            else
            {
                return String.Empty;
            }
        }
        public static string ReadIni(string Section, string Key, string NoText)
        {
            return ReadIniData(Section, Key, NoText, ".\\Config\\Config.ini");
        }
        #endregion

        #region 写Ini文件

        public static bool WriteIniData(string Section, string Key, string Value, string iniFilePath)
        {
            if (File.Exists(iniFilePath))
            {
                long OpStation = WritePrivateProfileString(Section, Key, Value, iniFilePath);
                if (OpStation == 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            else
            {
                return false;
            }
        }
        public static bool WritrIni(string Section, string Key, string Value)
        {
            return WriteIniData(Section, Key, Value, ".\\Config\\Config.ini");
        }
        #endregion

        #region 清空配置文件节
        ///   <summary> 
        ///   删除这个小节的所有设置项。 
        ///   </summary> 
        ///   <param   name= "sectionName "> 要删除的小节名。这个字串不区分大小写。 </param> 
        public static void EraseSection(string sectionName)
        {
            WritePrivateProfileString(sectionName, null, null, ".\\Config\\Config.ini");
        }
        #endregion

    }
    
    public class CommonLog
    {
        private static int cnt = 1;
        public static void LogWrite(string Msg)
        {

            string strPath;
            DateTime dt = DateTime.Now;
            if (dt.Hour == 0)
                cnt = 1;
            try
            {
                strPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log");
                if (!Directory.Exists(strPath))
                {
                    Directory.CreateDirectory(strPath);
                }

                DeleteLog(strPath);

                strPath = strPath + "\\" + dt.ToString("yyyyMMdd") + "-" + cnt + ".txt";
                FileInfo file = new FileInfo(strPath);
                if (file.Exists)
                {
                    //大于10M，写入新文件
                    if (file.Length > 1024 * 1024 * 10)
                    {
                        //file.Delete();
                        strPath = strPath + "\\" + dt.ToString("yyyyMMdd") + "-" + ++cnt + ".txt";
                    }
                }

                using (StreamWriter fileWriter = new StreamWriter(strPath, true))
                {
                    fileWriter.WriteLine(dt.ToString("HH:mm:ss ff") + " " + Msg);
                    fileWriter.Close();
                }
            }
            catch
            {

            }

        }
        public static void DeleteLog(string sLogPath)
        {
            DirectoryInfo dyInfo = new DirectoryInfo(sLogPath);
            //获取文件夹下所有的文件
            foreach (FileInfo feInfo in dyInfo.GetFiles())
            {
                //判断文件日期是否小于指定日期，是则删除
                if (feInfo.CreationTime < DateTime.Now.AddDays(-15))
                    feInfo.Delete();
            }
        }

    }
}
